package captcha

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wenlng/go-captcha/v2/slide"
	"product/common/condition"
	"product/common/validator"

	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CheckSlideCaptchaLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 检验滑动验证码
func NewCheckSlideCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckSlideCaptchaLogic {
	return &CheckSlideCaptchaLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckSlideCaptchaLogic) CheckSlideCaptcha(req *types.SlideCaptchaCheckReq) (resp *types.SlideCaptchaCheckResp, err error) {
	valid, err := validSlideInput(req)
	if !valid {
		resp.Ok = valid
		return resp, err
	}
	cachedSlide, err := l.svcCtx.Redis.GetCtx(l.ctx, req.CaptchaKey)
	if err != nil || validator.IsEmptyString(cachedSlide) {
		resp.Ok = false
		return resp, err
	}
	var slideCaptcha *slide.Block
	err = json.Unmarshal([]byte(cachedSlide), &slideCaptcha)
	if err != nil {
		resp.Ok = false
		return resp, errors.New("验证码数据解析失败")
	}
	checkFlag := slide.CheckPoint(int64(req.CaptchaCheckPonit.X), int64(req.CaptchaCheckPonit.Y), int64(slideCaptcha.X), int64(slideCaptcha.Y), 4)
	resp.Ok = checkFlag
	if !checkFlag {
		resp.Ok = false
		return resp, errors.New("验证码错误")
	}
	return resp, nil
}

func validSlideInput(req *types.SlideCaptchaCheckReq) (bool, error) {
	if validator.IsEmptyString(req.CaptchaKey) {
		return false, errors.New("captchaKey不能为空")
	}
	if !condition.Bool(req.CaptchaCheckPonit) {
		return false, errors.New("captchaCheckPonit不能为空")
	}
	return true, nil
}
